/**
 * Copyright (C), 2021-2023, 四信物联网有限公司
 * FileName: SpecialEventHandler
 * Author:   Chapin
 * Date:     2023/10/20 16:06
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.fourfaith.iot.beidou.handler;

import cn.hutool.core.util.HexUtil;
import com.fourfaith.iot.beidou.decodec.BeiDouContants;
import com.fourfaith.iot.beidou.decodec.BeiDouEncoder;
import com.fourfaith.iot.beidou.message.Message;
import com.fourfaith.iot.beidou.message.outbound.CCicrMessage;
import com.fourfaith.iot.beidou.session.SessionFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 〈〉
 *
 * @author Chapin
 * @create 2023/10/20
 * @since 1.0.0
 */
@Slf4j
public class SpecialEventHandler extends ChannelDuplexHandler {

    // 当客户端建立连接时触发连接事件
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 将channel通道和远程ip地址绑定
        Channel channel = ctx.channel();
        SessionFactory.getSession().bind(channel, BeiDouContants.BEI_DOU3);
        log.info("{}已经建立连接",ctx.channel());
    }

    // 当连接断开时触发 incative事件
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SessionFactory.getSession().unbind(ctx.channel());
        log.info("{}已经断开连接",ctx.channel());
    }

    // 捕捉到异常事件
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        SessionFactory.getSession().unbind(ctx.channel());
        log.info("{}已经异常断开，异常是{}",ctx.channel(),cause);
    }

    // 用来触发特殊事件
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        // 触发了读空闲事件
        if (event.state() == IdleState.READER_IDLE) {
            log.info("已经 30s 没有读到数据了");
//            ctx.channel().close();
        }
        // 触发了写空闲事件
        if(event.state() == IdleState.WRITER_IDLE){
           /* log.info("已经 60s 没有写数据了，发送一个心跳包");
            ByteBuf out = ctx.alloc().buffer();
            CCicrMessage cCicrMessage = new CCicrMessage();
            cCicrMessage.setInstructionType("0");
            cCicrMessage.setSubordinateUser("00");
            byte[] bytes = BeiDouEncoder.encodeToByte(cCicrMessage);
            log.info("发送CCICR：{}", HexUtil.encodeHexStr(bytes));
//            String decodeStr = "$CCTCQ,04202371,2,1,3,A47E7E060050622406A000320020020002241012160000F1F1005062240650F0F0241012160023190000003812118703B176,0*3C";
//            Object object = BeiDouEncoder.decode(decodeStr);
//            byte[] bytes = BeiDouEncoder.encodeToByte((Message) object);
//            log.info("定时发送心跳数据：{}", HexUtil.encodeHexStr(bytes));
            out.writeBytes(bytes);
            ctx.writeAndFlush(out);*/
        }

    }
}